package com.kjj.gift.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.kjj.gift.constants.LoginConstants;
import com.kjj.gift.domain.LoginUser;
import com.kjj.gift.domain.Permission;
import com.kjj.gift.dto.LoginDto;
import com.kjj.gift.exception.asserts.Assert;
import com.kjj.gift.mapper.LoginUserMapper;
import com.kjj.gift.mapper.PermissionMapper;
import com.kjj.gift.properties.Oauth2ClientDetails;
import com.kjj.gift.properties.Oauth2ClientDetailsProperties;
import com.kjj.gift.service.ILoginUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kjj.gift.util.AjaxResult;
import com.kjj.gift.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kjj
 * @since 2022-10-10
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {

    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private Oauth2ClientDetailsProperties oauth2ClientDetailsProperties;
    @Override
    public LoginUser selectByUsername(String username) {
        return loginUserMapper.loadByUsername(username);
    }

    @Override
    public AjaxResult loginAccount(LoginDto loginDto) {
        // jsr303 判空已经完成
        Integer type = loginDto.getType();
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        Wrapper<LoginUser> wrapper = new EntityWrapper<LoginUser>()
                .eq("username", username)
                .or()
                .eq("email", username)
                .or()
                .eq("tel", username)
                .andNew()
                .eq("type", type);
        List<LoginUser> loginUsers = loginUserMapper.selectList(wrapper);
        Assert.assertNotEmpty(JSON.toJSONString(loginUsers), "查不到该用户");
        Oauth2ClientDetails oauth2ClientDetails = oauth2ClientDetailsProperties.getOauth2ClientDetails(type);
        String clientId = oauth2ClientDetails.getClientId();
        String clientSecret = oauth2ClientDetails.getClientSecret();
        // 获取令牌url
        String url = "http://localhost:10030/services/auth/oauth/token?client_id" +
                "=%s&client_secret=%s&grant_type=password&username=%s&password=%s";
        url = String.format(url, clientId, clientSecret, username, password);
        System.out.println(url);
        // 通过Httpclient发送获取令牌的请求
        Map<String, String> result = HttpUtil.sendPost(url);

        // 判断令牌失效
        String error = result.get("error");
        String errorDescription = result.get("error_description");
        Assert.assertIsEmpty(error, errorDescription);
        System.out.println();
        //获取token
        String token = result.get("access_token");
        String refreshtToken = result.get("refresh_token");
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        resultMap.put("refreshtToken", refreshtToken);
        LoginUser loginUser = loginUsers.get(0);
        loginUser.setPassword("*******");
        resultMap.put("loginUser", loginUser);
        if (type== LoginConstants.LOGIN_TYPE_ADMIN) {
            List<Permission> permissions = permissionMapper
                    .selectPermissionsByUserId(loginUser.getId());
            List<String> sns = permissions.stream().map(permisson -> permisson.getSn())
                    .collect(Collectors.toList());
            resultMap.put("permissions", sns);
        }
        return AjaxResult.me().setResultObj(resultMap);
    }
}
